package controller.managedBeans;

import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.hibernate.Session;
import org.hibernate.jdbc.Work;


import model.entities.*;
import model.utils.JpaUtil;
import model.dao.*;

import org.hibernate.Session;
import org.hibernate.jdbc.Work;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.oasis.JROdtExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporterParameter;
import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import java.io.IOException;
import javax.faces.event.ActionEvent;
import java.util.HashMap;
import java.util.List;




@ManagedBean(name = "reportsBean")
@SessionScoped
public class ReportsBacking   implements Serializable {

	  private static final long serialVersionUID = 1L;
	
	@EJB
    private JpaUtil jpaUtil;
	
	@EJB
    private ItemsDao itemsFacade;
	
	
	private String item_code ;
	private String branch_code ;
	private String account_no ;
	private String value = "samy" ;
	private List<Item> items ;
	private Item selectedItem ;
	
	private List<Account> stockAccounts = new ArrayList();
	private String selectedAccountNo ;
	
	
	
	@ManagedProperty("#{itemsBean}")
	private ItemsBacking itemsBean;
	 
	 
	
	@PostConstruct
	public void onBeanLoad()
	{
		//jpaUtil.getConnection();
		//setValue("dfdfdfdfdf");
		FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		items = itemsBean.getItems();
		System.out.println("session bean @PostConstruct items size=" + items.size()); 
		stockAccounts = stockAccountsList();
		//items = itemsFacade.findAll();
	}

	public String doSomething()
	{
		///System.out.println("before");
		//jpaUtil.getConnection();
		//System.out.println("after");
		//setValue("Omarqqqqq");
		//return "reports" ;
		
		   try {
				pdf();
			} catch (JRException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		   
		   return null ;
	}
	
	
	public List<Account> stockAccountsList()
	{
		if(stockAccounts==null || stockAccounts.size()==0)
		{
			Account account = new Account();
			account.setAccount_no(1201107);
			account.setAccount_arabic_name("مخزون I PHONE");
			stockAccounts.add(account);
			
			
			 account = new Account();
			account.setAccount_no(12011011);
			account.setAccount_arabic_name("مخزون اجهزة متنوع");
			stockAccounts.add(account);
			
			
			 account = new Account();
			account.setAccount_no(1201201);
			account.setAccount_arabic_name("مخزون مستعمل نوكيا");
			stockAccounts.add(account);
			
			
			 account = new Account();
			account.setAccount_no(1201403);
			account.setAccount_arabic_name("مخزون مشغلات صوت");
			stockAccounts.add(account);
			
			
			
			 account = new Account();
			account.setAccount_no(1201101);
			account.setAccount_arabic_name("مخزون نوكيا");
			stockAccounts.add(account);
			
			
			 account = new Account();
			account.setAccount_no(1201203);
			account.setAccount_arabic_name("مخزون مستعمل متنوع");
			stockAccounts.add(account);
			
			 account = new Account();
				account.setAccount_no(1201401);
				account.setAccount_arabic_name("مخزون الكترونيات وكمبيوتر");
				stockAccounts.add(account);
			
				
				 account = new Account();
					account.setAccount_no(1201503);
					account.setAccount_arabic_name("مخزون شاحن");
					stockAccounts.add(account);
					
					
					 account = new Account();
						account.setAccount_no(12013101);
						account.setAccount_arabic_name("مخزون خطوط موبينيل");
						stockAccounts.add(account);
						
						
						 account = new Account();
							account.setAccount_no(1201402);
							account.setAccount_arabic_name("مخزون شاشات LCD");
							stockAccounts.add(account);
							
							
							 account = new Account();
								account.setAccount_no(1201202);
								account.setAccount_arabic_name("مخزون مستعمل I PHONE");
								stockAccounts.add(account);
								
								
								 account = new Account();
									account.setAccount_no(1201407);
									account.setAccount_arabic_name("مخزون آي بود");
									stockAccounts.add(account);
									
									
		}
		return stockAccounts ;
	}
	
	
	public List<String> filterItems(String prefix) 
	{
		System.out.println("prefix = '"+prefix+"'");
		List<String> result = new ArrayList<String>();
		for (Item item : getItems()) 
		{
			String suggestion = (item.getCode() + " " + item.getName()).toLowerCase() ;
			if (suggestion.contains(prefix.toLowerCase()))
			{
			   result.add(item.getCode()+ " --- "+item.getName());
		    }
		}
		return result;
	 }
	
	
	public String showStockValue()
	{
		   try {
			   initStockValue();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return null ;
	}
	
	
	
	
	
	public String doSomething2()
	{
		///System.out.println("before");
		//jpaUtil.getConnection();
		//System.out.println("after");
		//setValue("Omarqqqqq");
		//return "reports" ;
		
		   try {
			   pdfInLine();
			} catch (JRException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		   
		   return null ;
	}
	
	
    public void getConnection()
    {
    	
    	Session hibernateSession =	jpaUtil.getEntityManager().unwrap(Session.class);
    	final Connection myconnection ;
    	hibernateSession.doWork(
    		    new Work() {
    		        public void execute(Connection connection) throws SQLException 
    		        { 
    		        	//connection ;
    		        	System.out.println("hehewkejkjsdsd");
    		        System.out.println("connectionautocommit = " + connection.getAutoCommit());
    		        }
    		    }
    		);
    	
    }
	
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	////////////////////////////////////////////////
	
    JasperPrint jasperPrint;
    
	public void init()
	{
		System.out.println("begin init");
    	Session hibernateSession =	jpaUtil.getEntityManager().unwrap(Session.class);
    	hibernateSession.doWork(
    		    new Work() {
    		        public void execute(Connection connection) throws SQLException 
    		        { 
    		        	try {
    		        		preparJasperPrint(connection) ;
						} catch (JRException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							System.out.println(e.getMessage());
						}
    		        }
    		    }
    		);
    	
    	System.out.println("finish init");
	}

	
    
	public void init2()
	{
		System.out.println("begin init");
    	Session hibernateSession =	jpaUtil.getEntityManager().unwrap(Session.class);
    	hibernateSession.doWork(
    		    new Work() {
    		        public void execute(Connection connection) throws SQLException 
    		        { 
    		        	try {
    		        		
    		        	       HttpServletResponse response =(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
    		        	       ServletOutputStream servletOutputStream = response.getOutputStream();
    		        	       InputStream reportStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/reports/stock_serial.jasper");
    		        	       try
    		        	       {
			        	    	   Map parameters = new HashMap();
			        	    	   String logoRelativePath = File.separator + "resources" + File.separator + "images" + File.separator +  "select.jpg" ;
			        	    	   String LogoFullPath =  FacesContext.getCurrentInstance().getExternalContext().getRealPath(logoRelativePath);
			        	    	   parameters.put("image_path",LogoFullPath);   
			        	    	   
			        	    	   System.out.println("Before item_code=" + item_code);
			        	    	  // if(selectedItem!=null && selectedItem.getCode().trim()!="")
			        	    	  // item_code = item_code.substring( item_code.indexOf("---")+3 , item_code.length()).trim() ;

			        	    	   if(item_code !=null && item_code.trim()!="")
			        	    	   {
			        	    		   //parameters.put("item_code", selectedItem.getCode().trim());
				        	    	   String item_code_changed = item_code.substring(0 ,  item_code.indexOf("---")) ;
				        	    	   System.out.println("After item_code=" + item_code);
			        	    		   parameters.put("item_code", item_code_changed);
			        	    		   System.out.println("item_code=" + item_code);
			        	    	   }
     		        	    	   
			        	    	   if(branch_code!=null && branch_code.trim()!="")
			        	    	   {
			        	    		   parameters.put("branch_code", branch_code.trim() );
			        	    		   System.out.println("branch_code=" + branch_code);
			        	    	   }
    		        	    	      
    		        	    	   JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters , connection);
    		        	           response.setContentType("application/pdf");
    		        	           servletOutputStream.flush();
    		        	           servletOutputStream.close();
    		        	           FacesContext.getCurrentInstance().responseComplete();
    		        	       }
    		        	       catch (JRException e)
    		        	       {
    		        	         //handle the exception
    		        	    	   e.printStackTrace();
    		        	       }		
    		        		
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    		        }
    		    }
    		);
    	
    	System.out.println("finish init");
	}
	
	
	
	public void initStockValue()
	{
		System.out.println("begin init");
    	Session hibernateSession =	jpaUtil.getEntityManager().unwrap(Session.class);
    	hibernateSession.doWork(
    		    new Work() {
    		        public void execute(Connection connection) throws SQLException 
    		        { 
    		        	try {
    		        		
    		        	       HttpServletResponse response =(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
    		        	       ServletOutputStream servletOutputStream = response.getOutputStream();
    		        	       InputStream reportStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/reports/stock_value.jasper");
    		        	       try
    		        	       {
			        	    	   Map parameters = new HashMap();
			        	    	   String logoRelativePath = File.separator + "resources" + File.separator + "images" + File.separator +  "select.jpg" ;
			        	    	   String LogoFullPath =  FacesContext.getCurrentInstance().getExternalContext().getRealPath(logoRelativePath);
			        	    	   parameters.put("image_path",LogoFullPath);   
			        	    	   
			        	    	   

			        	    	   if(selectedAccountNo !=null && selectedAccountNo.trim()!="")
			        	    	   {
			        	    		   parameters.put("account_no", selectedAccountNo);
			        	    		   System.out.println("account_no=" + selectedAccountNo);
			        	    	   }
     		        	    	   
			        	    	   if(branch_code!=null && branch_code.trim()!="")
			        	    	   {
			        	    		   parameters.put("branch_code", branch_code.trim() );
			        	    		   System.out.println("branch_code=" + branch_code);
			        	    	   }
    		        	    	      
    		        	    	   JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameters , connection);
    		        	           response.setContentType("application/pdf");
    		        	           servletOutputStream.flush();
    		        	          // servletOutputStream.close();
    		        	           FacesContext.getCurrentInstance().responseComplete();
    		        	       }
    		        	       catch (JRException e)
    		        	       {
    		        	         //handle the exception
    		        	    	   e.printStackTrace();
    		        	       }		
    		        		
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    		        }
    		    }
    		);
    	
    	System.out.println("finish init");
	}
	
	
	
    public void preparJasperPrint(Connection connection) throws JRException{
        //JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(listOfUser);
    	System.out.println("begin  prepare");
        String  reportPath=  FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/report2.jasper");     
        jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),connection);
        System.out.println("finish prepare");
    }
    
 
    public void preparJasperPrintStockValue(Connection connection) throws JRException{
        //JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(listOfUser);
    	System.out.println("begin  prepare");
        String  reportPath=  FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/report2.jasper");     
        jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),connection);
        System.out.println("finish prepare");
    }
    
    
    
   public void pdf() throws JRException, IOException{
	   System.out.println("begin");
       init();
       HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
       httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
       System.out.println("going to generated");
       ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
       JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
       System.out.println("finish generation");
       FacesContext.getCurrentInstance().responseComplete();
   }
   
   
   public void pdfInLine() throws JRException, IOException{
	   System.out.println("begin");
       init2();
       //response.setContentType("text/html; charset=windows-1256");
      /* response.setContentType("application/pdf");
       response.addHeader("pragma", "no-cache");
       response.addHeader("cache-control", "no-cache");
       response.addHeader("expires", "0"); 
       JasperRunManager.run
       
       JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
       JasperRunManager.runReportToPdfStream(  reportContentInputStream,
								    		   response.getOutputStream(), 
								    		   report.getReportImages(), 
								    		   ConnectionPoolManager.getConnection());
								       
       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
       while((bytesRead = reportContentInputStream.read(buffer)) > -1) 
       {
             byteArrayOutputStream.write(buffer, 0, bytesRead);
       }
       reportBytes = byteArrayOutputStream.toByteArray();
       
       OutputStream outStream = response.getOutputStream();
       outStream.write(reportBytes);
       response.setContentLength((int)reportBytes.length);
       outStream.flush();

       HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
       httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
       System.out.println("going to generated");
       ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
       JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
       System.out.println("finish generation");
       FacesContext.getCurrentInstance().responseComplete();
       */
   }
   
   
   public void myPdf(ActionEvent event)
   {
	   System.out.println("myPDF");
	   try {
		pdf();
	} catch (JRException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
   }
   
   
    public void DOCX(ActionEvent actionEvent) throws JRException, IOException{
        init();
       HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
       httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.docx");
       ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
       JRDocxExporter docxExporter=new JRDocxExporter();
       docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
       docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream);
       docxExporter.exportReport();
       FacesContext.getCurrentInstance().responseComplete();
   }
     public void XLSX(ActionEvent actionEvent) throws JRException, IOException{
        init();
       HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
      httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.xlsx");
       ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
       JRXlsxExporter docxExporter=new JRXlsxExporter();
       docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
       docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream);
       docxExporter.exportReport();
       FacesContext.getCurrentInstance().responseComplete();
   }
      public void ODT(ActionEvent actionEvent) throws JRException, IOException{
       init();
       HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
      httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.odt");
       ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
       JROdtExporter docxExporter=new JROdtExporter();
       docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
       docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream);
       docxExporter.exportReport();
       FacesContext.getCurrentInstance().responseComplete();
   }
       public void PPT(ActionEvent actionEvent) throws JRException, IOException{
       init();
       HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
      httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pptx");
       ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
       JRPptxExporter docxExporter=new JRPptxExporter();
       docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
       docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream);
       docxExporter.exportReport();
       FacesContext.getCurrentInstance().responseComplete();
   }



	public String getItem_code() {
		return item_code;
	}



	public void setItem_code(String item_code) {
		this.item_code = item_code;
	}



	public String getBranch_code() {
		return branch_code;
	}



	public void setBranch_code(String branch_code) {
		this.branch_code = branch_code;
	}



	public String getAccount_no() {
		return account_no;
	}



	public void setAccount_no(String account_no) {
		this.account_no = account_no;
	}

	public List<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> items) {
		this.items = items;
	}

	public ItemsBacking getItemsBean() {
		return itemsBean;
	}

	public void setItemsBean(ItemsBacking itemsBean) {
		this.itemsBean = itemsBean;
	}

	public Item getSelectedItem() {
		return selectedItem;
	}

	public void setSelectedItem(Item selectedItem) {
		this.selectedItem = selectedItem;
	}

	public List<Account> getStockAccounts() {
		return stockAccounts;
	}

	public void setStockAccounts(List<Account> stockAccounts) {
		this.stockAccounts = stockAccounts;
	}

	public String getSelectedAccountNo() {
		return selectedAccountNo;
	}

	public void setSelectedAccountNo(String selectedAccountNo) {
		this.selectedAccountNo = selectedAccountNo;
	}
	
      
	
	
	
	
}
